package com.dmap.admin.service.backgroundv2.impl;

import com.dmap.admin.cache.IdentifyingCacheDao;
import com.dmap.admin.service.backgroundv2.IdentifyingCodeService;
import com.dmap.base.send.SMS.qcloudsms.QcloudSMSUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Random;

/**
 * \* User: helei
 * \* Date: 25/06/17
 * \* Description:发送验证码相关接口实现类
 * \
 */
@SuppressWarnings("Duplicates")
@Service
public class IdentifyingCodeServiceImpl implements IdentifyingCodeService {
    private static final Logger logger = LoggerFactory.getLogger(IdentifyingCodeServiceImpl.class);

    @Resource
    private IdentifyingCacheDao identifyingCacheDao;

    @Transactional
    @Override
    public String sendIdentifyingCode(String phoneNumber, String language, String countryCode) {
        String code = generateCode();
        boolean sendStatus = QcloudSMSUnit.sendRegisterVerifyCode(phoneNumber, code, language, countryCode);
        if (!sendStatus) {
            logger.warn("send sms error, phone is {}", phoneNumber);
            return null;
        }
        boolean cacheStatus = identifyingCacheDao.addIdentifyingCode(phoneNumber, code);
        if (!cacheStatus) {
            logger.warn("sms code cache error, phone is {}", phoneNumber);
            return null;
        }
        return code;
    }

    @Override
    public String getIdentifyingCode(String phoneNumber) {
        return identifyingCacheDao.getIdentifyingCode(phoneNumber);
    }

    // 生成一个4位数字的随机码
    private String generateCode() {
        Random random = new Random();
        int randomNum = random.nextInt(8999);
        int code = randomNum + 1000;
        return String.valueOf(code);
    }

}